package com.simga.library.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.simga.library.R;
import com.simga.library.base.IPresenter;
import com.simga.library.base.IView;
import com.simga.library.utils.AppManager;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.LogUtil;
import com.simga.library.utils.StatusBarUtil;
import com.simga.library.widget.DialogLoading;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;

import butterknife.ButterKnife;


public abstract class MBaseActivity<T extends IPresenter>
        extends RxAppCompatActivity {

    protected T presenter;
    // 弹出框
    private DialogLoading mLoading;
    protected MBaseActivity mContext;
    private Toast mToast;
    protected ImageView mIvBack;
    protected View mLine;
    protected ConstraintLayout mRlTitleBar;
    protected TextView mTvTitle;
    protected ImageView mIvRight;
    protected TextView mTvRight;
    protected int screenWidth;
    private ViewGroup bodyView;
    protected int screenHeight;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        mContext = this;
        int contentViewId = getViewId();
        setContentView(contentViewId);
        AppManager.get().addActivity(mContext);
        LogUtil.e("当前的Activity : " + this.getClass().getSimpleName());
        mLoading = new DialogLoading(mContext);
        if (getIntent() != null && getIntent().getExtras() != null) {
            onGetBundle(getIntent().getExtras());
        }
        presenter = createPresenter();
        if (this instanceof IView) {
            if (presenter != null) {
                presenter.bindView((IView) this);
            }
        }
        getAndroiodScreenProperty();
        init(savedInstanceState);
        initListener();
    }


    /**
     * 获取屏幕的匡高
     */
    private void getAndroiodScreenProperty() {
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        screenHeight = (int) (height / density);// 屏幕高度(dp)
    }

    private T createPresenter() {
        Type genType = this.getClass().getGenericSuperclass();
        if (genType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) genType;
            Type[] actualTypeArguments = type.getActualTypeArguments();
            Class<T> tClass = (Class<T>) actualTypeArguments[0];
            if (tClass != IPresenter.class) {
                try {
                    return tClass.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissLoading();
        mLoading = null;
    }

    /**
     * 是否设置状态栏字体图标为深色模式
     *
     * @return
     */
    protected boolean isSetStatusBarDarkMode() {
        return true;
    }

    public void setBackClick() {
        if (mIvBack != null) {
            mIvBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    protected void onGetBundle(Bundle bundle) {
    }

    // 设置标题
    public void setTitle(int res) {
        setTitle(getString(res));
    }

    // 设置标题
    public void setTitle(final String title) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mTvTitle != null) {
                    mTvTitle.setText(title);
                }
            }
        });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    // 设置右边文字
    public void setRightText(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mTvRight != null) {
                    mTvRight.setVisibility(View.VISIBLE);
                    mTvRight.setText(text);
                }
            }
        });
    }

    // 设置右边icon
    public void setRightImage(final int res) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mIvRight != null) {
                    mIvRight.setVisibility(View.VISIBLE);
                    mIvRight.setImageResource(res);
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void setContentView(int layoutResID) {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        if (isSetStatusBarDarkMode()) {
            StatusBarUtil.statusBarDarkMode(mContext);
        }
        if (isUseBaseTitleBar()) {
            bodyView = findViewById(Window.ID_ANDROID_CONTENT);
            View contentView = LayoutInflater.from(mContext).inflate(layoutResID, null);
            View titleBarView = LayoutInflater.from(mContext).inflate(R.layout.widget_title, null);
            FrameLayout.LayoutParams fl = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            fl.topMargin = getStateBar();
            bodyView.addView(contentView, fl);
            LinearLayout.LayoutParams titleBar = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, getStateBar());
            bodyView.addView(titleBarView, titleBar);
            mIvBack = findViewById(R.id.iv_back);
            mLine = findViewById(R.id.line);
            mRlTitleBar = findViewById(R.id.rl_title);
            mTvTitle = findViewById(R.id.tv_title);
            mTvRight = findViewById(R.id.tv_right);
            mIvRight = findViewById(R.id.iv_right);
            setBackClick();
        } else {
            super.setContentView(layoutResID);
        }
        ButterKnife.bind(this);
    }


    private int getStateBar() {
        try {
            Class c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x) + (int) Math.ceil((double) (50 * getResources().getDisplayMetrics().density));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (int) Math.ceil((double) (76 * getResources().getDisplayMetrics().density));
    }


    /**
     * 覆写finish方法，覆盖默认方法，加入切换动画
     */
    public void finish() {
        super.finish();
        overridePendingTransition(com.simga.library.R.anim.slide_right_in, com.simga.library.R.anim.slide_right_out);
    }

    /**
     * 不带切换动画
     */
    public void finishSimple() {
        super.finish();
    }

    public void finishResult(Intent intent) {
        setResult(RESULT_OK, intent);
        this.finish();
    }

    public void finishResult() {
        setResult(RESULT_OK);
        this.finish();
    }


    /**
     * 覆写startactivity方法，加入切换动画
     */
    public void startActivity(Bundle bundle, Class<?> target) {
        Intent intent = new Intent(this, target);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        // 动画切换
        overridePendingTransition(com.simga.library.R.anim.slide_left_in, com.simga.library.R.anim.slide_left_out);
    }

    /**
     * 带回调的跳转
     *
     * @param bundle
     * @param requestCode
     * @param target
     */
    public void startForResult(Bundle bundle, int requestCode, Class<?> target) {
        Intent intent = new Intent(this, target);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(com.simga.library.R.anim.slide_left_in, com.simga.library.R.anim.slide_left_out);
    }

    public void showToast(int res) {
        showToast(getString(res));
    }


    public void showToast(final Object message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView title;
                if (mToast == null) {
                    View layout = View.inflate(mContext, R.layout.layout_toast, null);
                    title = layout.findViewById(R.id.toast_tv);
                    title.setText(message != null ? message.toString() : "");
                    mToast = Toast.makeText(mContext, message + "", Toast.LENGTH_SHORT);
                    mToast.setGravity(Gravity.CENTER, 0, 0);
                    mToast.setDuration(Toast.LENGTH_SHORT);
                    mToast.setText(message != null ? message.toString() : "");
                    mToast.setView(layout);
                } else {
                    title = mToast.getView().findViewById(R.id.toast_tv);
                    title.setText(message.toString());
                }
                if (message != null) {
                    mToast.show();
                }
            }
        });
    }

    public void showLoading() {
        showLoading(true);
    }

    public void showLoading(final boolean cancelable) {
        if (mLoading != null && !mLoading.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLoading.show(cancelable);
                }
            });
        }
    }

    public void dismissLoading() {
        if (mLoading != null && mLoading.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLoading.dismiss();
                }
            });
        }
    }

    public void showErrorMsg(String code, String msg) {
        showToast(msg);
        if ("10001".equals(code)) {//未登录，失效
            sendBroadcast(new Intent(HawkKey.USER_LOGIN_OUT));
            return;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig != null && newConfig.fontScale != 1) {
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 让TextView的字体大小不跟随系统字体大小
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    protected boolean copy(String copyStr) {
        try {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    protected abstract int getViewId();

    protected abstract boolean isUseBaseTitleBar();

    protected abstract void init(Bundle savedInstanceState);

    protected void initListener() {}
}

